﻿using Newtonsoft.Json;
using Sunny.UI; 
using System.Text.RegularExpressions; 
using WinApp.i18n;
using WinApp.Model;
using WinApp.Model.AjaxResult; 
using WinApp.Until;
using WinApp.ViewModel;
using System;
using System.Text;
using System.Security.Cryptography;
using System.Threading;
using WinApp.Model.EF_Model;

namespace WinApp.View
{
    public partial class ExamList : UserControl
    {
        public WinApp _parent { get; set; }
        public int _currentListCount { get; set; } = 0;

        public UILabel _lbMore;
        public UILabel _lbNotData;

        public int _lastRowY { get; set; } = 0;
        private List<MyExaminationOutPutDto> _mainRows = new List<MyExaminationOutPutDto>();

        public SearchMyExaminationDto _SearchMyExaminationEntity = new SearchMyExaminationDto
        {
            ExaminationName = string.Empty,
            LastStatu = -1,
            LastStatuStr = "0",
            PageCondition = new Model.PageCondition()
            {
                PageIndex = 1,
                PageSize = 10,
                SortConditions = new List<Model.SortCondition> { new Model.SortCondition() { SortField = "BeginTime", ListSortDirection = Model.ListSortDirection.Ascending } }
            }
        };

        public ExamList()
        {
            InitializeComponent();
            this.lbSyncExamRecord.Text = Language.GetLang("syncExam");
            this.AutoScroll = true;
            this.panel1.AutoScroll = true;
            this.panel1.MouseWheel += UiPanel1_MouseWheel;
        }

        private void UiPanel1_MouseWheel(object? sender, MouseEventArgs e)
        {

        }

        private void ExamList_Load(object sender, EventArgs e)
        {

        }

        private void UiGroupBox1_Click(object? sender, EventArgs e)
        {
            UIGroupBox clickGroupBox = sender as UIGroupBox;
            if (clickGroupBox == null)
                return;

            var tagExamsSessionDto = clickGroupBox.Tag as TagExamsSessionDto;
            if (tagExamsSessionDto == null)
            {
                UIMessageDialog.ShowMessageDialog(Language.GetLang("notFindTag"), UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false);
                return;
            }

            var examinationRoundId = tagExamsSessionDto.LastSAAS_ExaminationRoundId == null ? -1 : tagExamsSessionDto.LastSAAS_ExaminationRoundId;
            var testPaperRoundId = tagExamsSessionDto.LastSAAS_TestPaperRoundId;
            //var checkResult = WebApiHelper.GetWebAPI<AjaxResult>($"api/Admin/Examination/CheckExaminationValid?enrollmentId={tagExamsSessionDto.ExamEnrollmentId}&testPaperId={tagExamsSessionDto.ExamTestPaperId}&examinationRoundId={examinationRoundId}&testPaperRoundId={tagExamsSessionDto.ExamTestPaperRoundId}");
            var checkResult = WebApiHelper.GetWebAPI<AjaxResult>($"api/Admin/Examination/CheckExaminationValid?enrollmentId={tagExamsSessionDto.Id}&testPaperId={tagExamsSessionDto.SAAS_TestPaperId}&examinationRoundId={examinationRoundId}&testPaperRoundId={testPaperRoundId}");
            if (checkResult.Type != AjaxResultType.Success)
            {
                if (checkResult.Type == AjaxResultType.Info)
                {
                    string strCheckMsg = string.Empty;
                    switch (checkResult.Content)
                    {
                        case "1107":
                            strCheckMsg = Language.GetLang("page_examNotStart");
                            break;
                        case "1108":
                            strCheckMsg = Language.GetLang("page_examEnd");
                            break;
                        case "1109":
                            strCheckMsg = Language.GetLang("page_examIsPass");
                            break;
                        case "1111":
                            strCheckMsg = Language.GetLang("page_examFailedAndNoCount");
                            break;
                        case "1113":
                            strCheckMsg = Language.GetLang("page_examInComplete");
                            break;
                        case "1112":
                            strCheckMsg = Language.GetLang("page_examIsWaitRead");
                            break;
                        case "1103":
                            strCheckMsg = Language.GetLang("page_examAddressIsError");
                            break;
                        case "1114":
                            strCheckMsg = Language.GetLang("page_noExamCount");
                            break;
                        case "1115":
                            strCheckMsg = Language.GetLang("page_examIsCanNotAgainToExam");
                            break;
                        case "1116":
                            strCheckMsg = Language.GetLang("page_rengongkaikao");
                            break;
                        case "1117":
                            var strExamBuKaoJianGe = Language.GetLang("page_examBuKaoTimeJianGe");
                            double.TryParse(checkResult.Data.ToString(), out double seconds);

                            strExamBuKaoJianGe = strExamBuKaoJianGe.Replace("{{examTimeJianGe}}", UtilHelper.DoubleTimeToString(seconds));
                            strCheckMsg = strExamBuKaoJianGe;
                            break;
                        case "1135":
                        case "ConditionNotComplete":
                            strCheckMsg = Language.GetLang("page_examConditionIsNotComplete");
                            break;

                        case "1110":
                            strCheckMsg = "";
                            break;
                        case "1169":
                            strCheckMsg = Language.GetLang("page_notMeetTempTimeInterval");
                            break;
                        default:
                            strCheckMsg = checkResult.Content;
                            break;
                    }

                    if (!strCheckMsg.IsNullOrEmpty())
                    {
                        UIMessageDialog.ShowMessageDialog(strCheckMsg, UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false);
                        return;
                    }
                    else
                    {
                        _parent.OpenExamPlay(tagExamsSessionDto);
                    }
                }
                else
                {
                    UIMessageDialog.ShowMessageDialog(checkResult.Content, UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false);
                    return;
                }
            }
        }

        public void LoadPanellData()
        {
            LoadingHelper.ShowLoadingScreen();//显示
            this.panel1.Controls.Clear();
            _lastRowY = 0;
            _currentListCount = 0;
            _lbMore = new UILabel();
            _lbMore.Text = "More";
            _lbMore.ForeColor = Color.Blue;
            _lbMore.Cursor = Cursors.Hand;
            _lbMore.TextAlign = ContentAlignment.MiddleCenter;
            _lbMore.Location = new Point(0, 0);
            _lbMore.Click += _lbMore_Click; ;
            _lbMore.Visible = false;
            this.panel1.Controls.Add(_lbMore);

            _lbNotData = new UILabel();
            _lbNotData.Text = "No more data available";
            _lbNotData.Cursor = Cursors.Hand;
            _lbNotData.TextAlign = ContentAlignment.MiddleCenter;
            _lbNotData.Location = new Point(0, 0);
            _lbNotData.Width = 200;
            _lbNotData.Visible = false;
            this.panel1.Controls.Add(_lbNotData);

            _SearchMyExaminationEntity.PageCondition.PageIndex = 1;
            _mainRows = new List<MyExaminationOutPutDto>();
            QueryData();

            LoadingHelper.CloseForm();//关闭

        }

        public void QueryData()
        {
            // 进行耗时操作，例如加载接口
            PageDataRow result = ExamListModel.ReadByMyExamination(_SearchMyExaminationEntity);
            if (result == null || result.Total <= 0)
            {
                _lbMore.Visible = false;
                _lbNotData.Visible = true;
                _lbNotData.Location = new Point(450, 20 + 30);
                return;
            }
            List<MyExaminationOutPutDto> DataRows = JsonConvert.DeserializeObject<List<MyExaminationOutPutDto>>(result.Rows.ToString());
            if (DataRows == null || DataRows.Count <= 0)
            {
                _lbMore.Visible = false;
                _lbNotData.Visible = true;
                _lbNotData.Location = new Point(450, 20 + 30);
                return;
            }


            for (int i = 0; i < DataRows.Count; i++)
            {
                UIGroupBox gbox = new UIGroupBox();
                gbox.Width = 1035;
                gbox.Height = 140;
                gbox.Text = (_currentListCount + 1).ToString();
                //gbox.Tag = DataRows[i].Id.ToString();

                TagExamsSessionDto tagExamsSessionDto = new TagExamsSessionDto()
                {
                    BeginTime = DataRows[i].BeginTime,
                    EndTime = DataRows[i].EndTime,
                    ExaminationDescription = DataRows[i].ExaminationDescription,
                    ExaminationDuration = DataRows[i].ExaminationDuration,
                    Id = DataRows[i].Id,
                    IsResume = DataRows[i].IsResume,
                    LastSAAS_ExaminationRoundId = DataRows[i].LastSAAS_ExaminationRoundId,
                    LastSAAS_TestPaperRoundId = DataRows[i].LastSAAS_TestPaperRoundId,
                    LastSAAS_TestPaperRoundName = DataRows[i].LastSAAS_TestPaperRoundName,
                    LastScore = DataRows[i].LastScore,
                    LastStatu = DataRows[i].LastStatu,
                    SAAS_ExaminationId = DataRows[i].SAAS_ExaminationId,
                    SAAS_ExaminationName = DataRows[i].SAAS_ExaminationName,
                    SAAS_TestPaperId = DataRows[i].SAAS_TestPaperId,
                    SurfacePlot = DataRows[i].SurfacePlot,
                    UserId = DataRows[i].UserId

                    //ExamEnrollmentId = DataRows[i].Id,
                    //ExamTestPaperId = DataRows[i].SAAS_TestPaperId,
                    //ExamTestPaperRoundId = DataRows[i].LastSAAS_TestPaperRoundId.HasValue ? DataRows[i].LastSAAS_TestPaperRoundId.Value : -1,
                    //StrStartTime = DataRows[i].BeginTime.ToString("yyyy.MM.dd"),
                    //StrEndTime = DataRows[i].EndTime.HasValue ? DataRows[i].EndTime.Value.ToString("yyyy.MM.dd") : "None",
                    //LastSAAS_ExaminationRoundId = DataRows[i].LastSAAS_ExaminationRoundId,

                };
                gbox.Tag = tagExamsSessionDto;


                if (_lastRowY != 0)
                {
                    gbox.Location = new Point(5, _lastRowY - panel1.VerticalScroll.Value + 140 + 30);
                }
                else
                {
                    //30预留的是同步按钮的高度，140是group的高度；
                    gbox.Location = new Point(3, i * 140 + 30);
                    //gbox.Location = new Point(5, i * 140);
                }
                _lastRowY = _currentListCount * 140;
                gbox.Click += UiGroupBox1_Click;

                this.panel1.Controls.Add(gbox);
                FillInPanell(gbox, DataRows[i]);

                _currentListCount++;
            }

            if (_currentListCount < result.Total)
            {

                _lbMore.Visible = true;
                _lbMore.Location = new Point(450, _lastRowY - panel1.VerticalScroll.Value + 140 + 30);
            }
            else
            {
                _lbMore.Visible = false;
                _lbNotData.Visible = true;
                _lbNotData.Location = new Point(450, _lastRowY - panel1.VerticalScroll.Value + 140 + 30);
            }
        }


        public void FillInPanell(UIGroupBox gb, MyExaminationOutPutDto item)
        {
            var defaultCbtCover = FileHelper.loadImageFromLocalPath(@"FileFolder/Icon/book.png");
            if (!string.IsNullOrEmpty(item.SurfacePlot))
            {
                //SurfacePlot  https://test.astrom.cn/fileFolder/surfaces/test/defaultTestPaperSurface.png
                defaultCbtCover = FileHelper.LoadImageFromWebUriAsync(GlobalVariables.WebIp + "fileFolder/surfaces/" + WebApiHelper._Tenancy + "/" + item.SurfacePlot);
            }

            //左侧图像
            PictureBox pictureBox = new PictureBox();
            pictureBox.Width = 107;
            pictureBox.Height = 51;
            pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
            pictureBox.Location = new Point(25, 50);
            pictureBox.Image = defaultCbtCover;
            gb.Controls.Add(pictureBox);

            //title
            UILabel lbTitle = new UILabel();
            lbTitle.Location = new Point(151, 23);
            lbTitle.Width = 300;
            lbTitle.Text = item.SAAS_ExaminationName;
            lbTitle.Font = new Font(lbTitle.Font.Name, lbTitle.Font.Size, FontStyle.Bold);
            gb.Controls.Add(lbTitle);

            //currentRound
            UILabel lbCurrentRound = new UILabel();
            lbCurrentRound.Location = new Point(151, 51);
            lbCurrentRound.Width = 300;
            string CourseUnitStr = Language.GetLang("currentRound") + item.LastSAAS_TestPaperRoundName;
            lbCurrentRound.Text = CourseUnitStr;
            gb.Controls.Add(lbCurrentRound);

            //duration
            UILabel lbDuration = new UILabel();
            lbDuration.Location = new Point(151, 80);
            lbDuration.Width = 300;
            lbDuration.ForeColor = Color.Red;
            string DurationStr = Language.GetLang("duration") + UtilHelper.DoubleTimeToString(item.ExaminationDuration);
            lbDuration.Text = DurationStr;
            gb.Controls.Add(lbDuration);

            //time
            UILabel lbTime = new UILabel();
            lbTime.Location = new Point(150, 109);
            lbTime.Width = 500;
            var timeStr = string.Empty;
            var beginTime = TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(item.BeginTime), TimeZoneInfo.Local);
            timeStr = Language.GetLang("startTime") + beginTime.ToString("yyyy-MM-dd HH:mm:ss");
            if (item.EndTime != null)
            {
                var endTime = TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(item.EndTime), TimeZoneInfo.Local);
                timeStr += " - " + Language.GetLang("endTime") + beginTime.ToString("yyyy-MM-dd HH:mm:ss");
            }
            lbTime.Text = timeStr;
            gb.Controls.Add(lbTime);

            UILabel lbStatus = new UILabel();
            lbStatus.Location = new Point(450, 51);
            lbStatus.Width = 300;
            var statusStr = string.Empty;

            switch (item.LastStatu)
            {
                case 0:
                case 1:
                case 2:
                    lbStatus.ForeColor = Color.Black;
                    break;

                case 3:
                    lbStatus.ForeColor = Color.Green;
                    break;

                case 4:
                    lbStatus.ForeColor = Color.Red;
                    break;

                case 5:
                    lbStatus.ForeColor = Color.Black;
                    break;
                case 6:
                    lbStatus.ForeColor = Color.Orange;
                    break;
                case 7:
                    lbStatus.ForeColor = Color.BlueViolet;
                    break;
                default:
                    lbStatus.ForeColor = Color.Black;
                    break;
            }
            // statusStr;
            lbStatus.Text = UtilHelper.GetExamStatusStr(item.LastStatu);
            lbStatus.Font = new Font(lbTitle.Font.Name, lbTitle.Font.Size, FontStyle.Bold);
            gb.Controls.Add(lbStatus);

            //在线时显示下载按钮
            if (GlobalVariables.SystemSwitchModel == SwitchMode.OnLine) {
                UIAvatar uIAvatar = new UIAvatar();
                uIAvatar.AvatarSize = 35;
                uIAvatar.Width = 42;
                uIAvatar.Height = 37;
                uIAvatar.Shape = UIShape.Circle;
                uIAvatar.Symbol = 61465;
                uIAvatar.FillColor = Color.Transparent;
                uIAvatar.Location = new Point(935, 60);
                uIAvatar.Click += imgDownloadExam;
                uIAvatar.Tag = item;
                gb.Controls.Add(uIAvatar);
            } 
        }

        private void _lbMore_Click(object? sender, EventArgs e)
        {
            _SearchMyExaminationEntity.PageCondition.PageIndex = _SearchMyExaminationEntity.PageCondition.PageIndex + 1;
            QueryData();
        }

        private void lbSyncExamRecord_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            UIMessageDialog.ShowMessageDialog("Ok", UILocalize.SuccessTitle, showCancelButton: false, UIStyle.Green, false);
            //ShowSuccessDialog("正确信息提示框");
        }

        #region 下载试卷
        private void imgDownloadExam(object? sender, EventArgs e)
        {
            UIAvatar? clickGroupBox = sender as UIAvatar;
            if (clickGroupBox == null)
                return;

            var model = clickGroupBox.Tag as MyExaminationOutPutDto;
            if (model == null)
            {
                UIMessageDialog.ShowMessageDialog(Language.GetLang("notFindTag"), UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false);
                return;
            }
            var result = WebApiHelper.GetWebAPI<AjaxResult>($"api/Admin/Examination/GetExaminationAllData?examinationId={model.SAAS_ExaminationId}&testPaperId={model.SAAS_TestPaperId}");
            if (result.Succeeded())
            {
                string pattern = @"^(\s|')+| (\s | ')+$";
                string replacement = "";
                Regex regex = new Regex(pattern, RegexOptions.Compiled);
                var resultData = result.Data.ToString();
                var str = regex.Replace(resultData, replacement);
                //判断本地是否已经下载过？
                var dataobject = GetExamContentDataAsync(model.Id);
                if (dataobject == null)
                {
                    dataobject = new ExamContentData()
                    {
                        Id = model.Id,
                        SAAS_ExaminationId = model.SAAS_ExaminationId,
                        UserId = model.UserId,
                        LastSAAS_TestPaperRoundName = model.LastSAAS_TestPaperRoundName,
                        LastSAAS_TestPaperRoundId = model.LastSAAS_TestPaperRoundId,
                        SAAS_TestPaperId = model.SAAS_TestPaperId,
                        LastSAAS_ExaminationRoundId = model.LastSAAS_ExaminationRoundId,
                        IsResume = model.IsResume?1:0,
                        ExamType = model.ExamType, 
                        ExamContent123 = str,
                    };
                }
                else
                {
                    dataobject.ExamContent123 = str; 
                }
                //点击下载的时候，离线要显示
                SaveExam(model);
                ExamSourceDownloadAsync(model, dataobject);
            }
            else {
                UIMessageDialog.ShowMessageDialog(Language.GetLang("Cachefailed"), UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false);
                return;
            }
        }

        private void ExamSourceDownloadAsync(MyExaminationOutPutDto exam, ExamContentData model) {
            try
            {
                if (model.ExamContent123 == null)
                {
                    UIMessageDialog.ShowMessageDialog(Language.GetLang("Notgetexamcache"), UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false); 
                    return;
                }
                var base64UrlEncodedString = model.ExamContent123.Replace("\"", ""); 
                string tempJson = Base64UrlEncoderDecode(base64UrlEncodedString);

                string pattern = @"\.\./[^\s]*\.(png|jpg)";
                MatchCollection matches = Regex.Matches(tempJson, pattern);

                foreach (Match match in matches)
                { 

                    string imagePath = match.Value;
                    var tempImagePath = imagePath;
                    if (imagePath.Contains("..")) {
                        tempImagePath = imagePath.Replace("../", GlobalVariables.WebIp + "/");
                    }

                    var localImagePath = HttpDownloadFileAsync(tempImagePath, exam);
                    tempJson = tempJson.Replace(imagePath, localImagePath.Result);
                } 
                var newJsonStr = Base64UrlEncoderEncode(tempJson); ;
                model.ExamContent123 = newJsonStr;
                SaveExamContentData(model);
                UIMessageDialog.ShowMessageDialog(Language.GetLang("CacheComplete"), UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false); 
            }
            catch (Exception ex)
            {
                UIMessageDialog.ShowMessageDialog(Language.GetLang("Unkownerror"), UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false); 
                return;
            }
        }
        private string Base64UrlEncoderEncode(string tempJson) {
            byte[] bytesToEncode = Encoding.UTF8.GetBytes(tempJson);

            string base64EncodedString = Convert.ToBase64String(bytesToEncode);

            string base64UrlEncodedString = base64EncodedString.Replace('+', '-').Replace('/', '_').TrimEnd('=');
            return base64UrlEncodedString;
        }
        private string Base64UrlEncoderDecode(string base64UrlEncodedString) {
            string base64EncodedString = base64UrlEncodedString.Replace('-', '+').Replace('_', '/');
            while (base64EncodedString.Length % 4 != 0)
            {
                base64EncodedString += '=';
            }

            byte[] decodedBytes = Convert.FromBase64String(base64EncodedString);

            string tempJson = Encoding.UTF8.GetString(decodedBytes);
            return tempJson;
        }
        private async Task<string> HttpDownloadFileAsync(string imageUrl, MyExaminationOutPutDto exam)
        { 
            string documentsPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), $"SAASImage/{exam.Id}");
            string pattern = @"https?://[^/]+/";
            var filePath = Regex.Replace(imageUrl, pattern, "");
            var downloadFilename = Path.Combine(documentsPath, filePath);
            var checkpointDir = downloadFilename + ".dcp";
            var downloadDirectoryName = Path.GetDirectoryName(downloadFilename);

            if (!Directory.Exists(downloadDirectoryName))
            {
                Directory.CreateDirectory(downloadDirectoryName);
            }
            if (File.Exists(downloadFilename))
            {
                return downloadFilename;
            }
            var result = await Task.Run(async () =>
            {
                using (HttpClient client = new HttpClient())
                {
                    try
                    {
                        HttpResponseMessage response = await client.GetAsync(imageUrl);

                        response.EnsureSuccessStatusCode();

                        using (HttpContent content = response.Content)
                        {
                            byte[] imageBytes = await content.ReadAsByteArrayAsync();
                            System.IO.File.WriteAllBytes(downloadFilename, imageBytes);
                        }
                        return downloadFilename;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("下载图片时出现错误：" + ex.Message);
                    }
                    return await Task.FromResult<string>(null);
                }
            });
            return result;
        }

        private void SaveExam(MyExaminationOutPutDto model) {
            using (var db = new SqlLiteDbContext())
            {
                var currentExam = db.Exams.Find(model.Id);
                if (currentExam == null)
                {
                    db.Exams.Add(new Exam
                    {
                        Id = model.Id,
                        SAAS_ExaminationId = model.SAAS_ExaminationId,
                        UserId = model.UserId,
                        SurfacePlot = model.SurfacePlot,
                        LastSAAS_TestPaperRoundName = model.LastSAAS_TestPaperRoundName,
                        LastSAAS_TestPaperRoundId = model.LastSAAS_TestPaperRoundId,
                        LastScore = model.LastScore,
                        SAAS_ExaminationName = model.SAAS_ExaminationName,
                        LastStatu = model.LastStatu,
                        ExaminationDescription = model.ExaminationDescription,
                        BeginTime = model.BeginTime.Ticks / TimeSpan.TicksPerMillisecond,
                        EndTime = model.EndTime.HasValue ? model.EndTime.Value.Ticks / TimeSpan.TicksPerMillisecond : null,
                        ExaminationDuration = model.ExaminationDuration,
                        SAAS_TestPaperId = model.SAAS_TestPaperId,
                        LastSAAS_ExaminationRoundId = model.LastSAAS_ExaminationRoundId,
                        IsResume = model.IsResume ? 1 : 0,
                        ExamType = model.ExamType,
                        IsAppOfflineDownload = model.IsAppOfflineDownload ? 1 : 0,
                        IsCache = model.IsCache ? 1 : 0
                    });
                    db.SaveChanges();
                }
                else
                {
                    currentExam.Id = model.Id;
                    currentExam.SAAS_ExaminationId = model.SAAS_ExaminationId;
                    currentExam.UserId = model.UserId;
                    currentExam.SurfacePlot = model.SurfacePlot;
                    currentExam.LastSAAS_TestPaperRoundName = model.LastSAAS_TestPaperRoundName;
                    currentExam.LastSAAS_TestPaperRoundId = model.LastSAAS_TestPaperRoundId;
                    currentExam.LastScore = model.LastScore;
                    currentExam.SAAS_ExaminationName = model.SAAS_ExaminationName;
                    currentExam.LastStatu = model.LastStatu;
                    currentExam.ExaminationDescription = model.ExaminationDescription;
                    currentExam.BeginTime = model.BeginTime.Ticks / TimeSpan.TicksPerMillisecond;
                    currentExam.EndTime = model.EndTime.HasValue ? model.EndTime.Value.Ticks / TimeSpan.TicksPerMillisecond : null;
                    currentExam.ExaminationDuration = model.ExaminationDuration;
                    currentExam.SAAS_TestPaperId = model.SAAS_TestPaperId;
                    currentExam.LastSAAS_ExaminationRoundId = model.LastSAAS_ExaminationRoundId;
                    currentExam.IsResume = model.IsResume ? 1 : 0;
                    currentExam.ExamType = model.ExamType;
                    currentExam.IsAppOfflineDownload = model.IsAppOfflineDownload ? 1 : 0;
                    currentExam.IsCache = model.IsCache ? 1 : 0;
                    db.SaveChanges();
                }

            }
            
        }

        private void SaveExamContentData(ExamContentData dto)
        { 
            using (var db = new SqlLiteDbContext())
            {
                var currentExamContentData = db.ExamContentDatas.Find(dto.Id);
                if (currentExamContentData == null)
                {
                    db.ExamContentDatas.Add(dto);
                    db.SaveChanges();
                }
                else {
                    currentExamContentData.Id = dto.Id;
                    currentExamContentData.SAAS_ExaminationId = dto.SAAS_ExaminationId;
                    currentExamContentData.UserId = dto.UserId;
                    currentExamContentData.LastSAAS_TestPaperRoundName = dto.LastSAAS_TestPaperRoundName;
                    currentExamContentData.LastSAAS_TestPaperRoundId = dto.LastSAAS_TestPaperRoundId;
                    currentExamContentData.SAAS_TestPaperId = dto.SAAS_TestPaperId;
                    currentExamContentData.LastSAAS_ExaminationRoundId = dto.LastSAAS_ExaminationRoundId;
                    currentExamContentData.IsResume = dto.IsResume;
                    currentExamContentData.ExamType = dto.ExamType;
                    currentExamContentData.ExamContent123 = dto.ExamContent123; 
                    db.SaveChanges();
                }
                   
            }
        }
        public ExamContentData GetExamContentDataAsync(int Id)
        {
            using (var db = new SqlLiteDbContext())
            {
                return db.ExamContentDatas.Find(Id);
            } 
        } 
        #endregion
    }
}
